package com.lcy.springtest.conf;


import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.EmbeddedValueResolverAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.context.annotation.PropertySource;
import org.springframework.util.StringValueResolver;

import com.mchange.v2.c3p0.ComboPooledDataSource;

/**
 * @author lichenyang
 *
 *  加了环境标识的bean 只有这个环境被激活的时候才能注册到容器中
 *	如果环境标识位 @Profile("default") 则默认使用这个
 *
 *  @Profile("") 还可以写在类上面 表示 只有是这个环境的时候,整个配置类才生效
 *  没有标注 @Profile("") 的组件 在任何条件下都能被加载
 */
//@Profile("test")
@Configuration
@PropertySource(value = {"classpath:/dbconfig.properties"})
public class ProfileConfig implements EmbeddedValueResolverAware{
	@Value("${db.user}")
	private String user;

	private StringValueResolver valueResolver;

	private String  driverClass;

	@Override
	public void setEmbeddedValueResolver(StringValueResolver resolver) {
		this.valueResolver = resolver;
		driverClass = valueResolver.resolveStringValue("${db.driverClass}");
	}

	@Profile("test")
	@Bean("testDataSource")
	public DataSource dataSourceTest(@Value("${db.password}")String pwd) throws Exception{
		ComboPooledDataSource dataSource = new ComboPooledDataSource();
		System.out.println("test环境");
		dataSource.setUser(user);
		dataSource.setPassword(pwd);
		dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/test");
		dataSource.setDriverClass(driverClass);
		return dataSource;
	}

	@Profile("dev")
	@Bean("devDataSource")
	public DataSource dataSourceDev(@Value("${db.password}")String pwd) throws Exception{
		ComboPooledDataSource dataSource = new ComboPooledDataSource();
		System.out.println("dev环境");
		System.out.println(user);
		dataSource.setUser(user);
		dataSource.setPassword(pwd);
		dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/ssm_crud");
		dataSource.setDriverClass(driverClass);
		return dataSource;
	}
}



